package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

@Controller
@RequestMapping("/code")
public class CodeController {

    @RequestMapping("/getCodeImage")
    public void getCodeImage(OutputStream out,HttpSession session)throws Exception{

        Random random=new Random();

        //在内存中创建一个画图板
        BufferedImage image=new BufferedImage(70,30,BufferedImage.TYPE_INT_RGB);

        //获得画笔
        Graphics graphics=image.getGraphics();

        //设置画笔颜色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));

        //画一个带填充色的矩形作为背景
        graphics.fillRect(0,0,70,30);


        //设置画笔颜色
        graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));

        //设置字体
        graphics.setFont(new Font("Courier New",Font.BOLD+Font.ITALIC,18));

        //生成一个5位的随机字符串，字符串中包括[a-z][A-Z][0-9]
        String s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        StringBuffer code=new StringBuffer();


        for (int i = 0; i < 5; i++) {
            code.append(s.charAt(random.nextInt(s.length())));
        }

        System.out.println("code = " + code);

        session.setAttribute("code",code.toString());

        //将文字写到图片上
        graphics.drawString(code.toString(),5,20);

        //画3条干扰下
        for (int i = 0; i < 3; i++) {
            //设置画笔颜色
            graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));

            //画线
            graphics.drawLine(random.nextInt(71),random.nextInt(31),random.nextInt(71),random.nextInt(31));
        }


        ImageIO.write(image,"jpeg",out);
    }

    @RequestMapping(value = "/validateCode",produces = "text/plain;charset=utf-8")
    public @ResponseBody String validateCode(String code,HttpSession session){
        System.out.println("CodeController.validateCode()");

        String sessionCode= (String) session.getAttribute("code");

        if(sessionCode!=null&&sessionCode.equalsIgnoreCase(code)){
            return "验证码正确";
        }
        return "验证码错误";

    }


}
